package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(timeout = 200000)
public class VisitorsApiImpl implements VisitorsApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RecommendUserApi recommendUserApi;

    @Override
    public List<Visitors> queryVisitors(Long userId, int top) {
        //db.visitors.find({userId:1}).sort({date:-1}).limit(5)
        // 查询条件
        Query query = Query.query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(top);
        return getVisitors(query);
    }

    @Override
    public List<Visitors> queryVisitors(Long userId, Long time) {
        //db.visitors.find({userId:1,date:{$gt:100}}).sort({date:-1})
        // 查询条件
        Query query = Query.query(
                Criteria.where("userId").is(userId)
                .and("date").gt(time)
        );
        query.with(Sort.by(Sort.Order.desc("date")));
        // 查询
        return getVisitors(query);
    }

    private List<Visitors> getVisitors(Query query) {
        // 查询
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        if (visitorsList != null && visitorsList.size()>0) {
            for (Visitors visitors : visitorsList) {
                Long score = recommendUserApi.queryScore(visitors.getUserId(), visitors.getVisitorUserId());
                visitors.setScore(score.doubleValue());
            }
        }
        return visitorsList;
    }

}
